package com.easy.activiti;

import com.easy.activiti.ext.IActivitiListener;
import com.easy.activiti.ext.OnActivitiEvent;
import com.easy.activiti.listener.EventHandler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhouchuang
 * 2024-11-05 14:19:28
 * 采集所有的activiti服务，并注册到activitiServerContextUtil
 */

@Configuration
public class RegisterActivitiServerAutoConfiguration implements BeanPostProcessor {


    @PostConstruct
    public void initialize() {
        System.out.println("==============RegisterActivitiServerAutoConfiguration initialize==============");
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if(bean instanceof IActivitiListener){
            OnActivitiEvent onActivitiEvent = bean.getClass().getAnnotation(OnActivitiEvent.class);
            if(onActivitiEvent !=null){
                String key = onActivitiEvent.value();
                Class<?>[] interfaces = bean.getClass().getInterfaces();
                for (Class<?> anInterface : interfaces) {
                    if(anInterface == IActivitiListener.class){
                        Method[] methods = anInterface.getDeclaredMethods();
                        for (Method method : methods) {
                            method.setAccessible(true);
                            EventHandler.Context.register(key+method.getName(),bean,method);
                        }
                        break;
                    }
                }
                //判断方法上面是否有注解
                List<Method> methodList = Arrays.stream(bean.getClass().getDeclaredMethods()).filter(t->t.isAnnotationPresent(OnActivitiEvent.class)).collect(Collectors.toList());
                for (Method method : methodList) {
                    method.setAccessible(true);
                    OnActivitiEvent annotation = method.getAnnotation(OnActivitiEvent.class);
                    String name = annotation.name();
                    OnActivitiEvent.Type type = annotation.type();
                    EventHandler.Context.register(key+name+type.name(),bean,method);
                }
            }
        }
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }
}
